<template>
  <div class="user-profile">
    <h1>个人资料</h1>
    <el-form :model="userInfo" :rules="rules" ref="userForm" label-width="100px" class="profile-form">
      <el-form-item label="用户ID" prop="id">
        <el-input v-model="userInfo.id" disabled></el-input>
      </el-form-item>
      
      <el-form-item label="用户名" prop="name">
        <el-input v-model="userInfo.name"></el-input>
      </el-form-item>
      
      <el-form-item label="修改密码" prop="password">
        <el-input v-model="userInfo.password" type="password" show-password></el-input>
      </el-form-item>
      
      <el-form-item label="角色" prop="role">
        <el-select v-model="userInfo.role" disabled>
          <el-option label="管理员" value="admin"></el-option>
          <el-option label="员工" value="employee"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-select v-model="userInfo.status" disabled>
          <el-option label="在职" value="active"></el-option>
          <el-option label="离职" value="inactive"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">保存修改</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import store from '../../store'

export default {
  name: 'UserProfile',
  data() {
    return {
      userInfo: {
        id: '',
        name: '',
        password: '',
        role: '',
        status: ''
      },
      originalInfo: {},
      rules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { min: 6, message: '密码长度至少为 6 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          this.originalInfo = { ...this.userInfo }
          alert('保存成功！')
        } else {
          alert('表单验证失败，请检查输入！')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.userForm.resetFields()
      if (this.originalInfo.id) {
        this.userInfo = { ...this.originalInfo }
      } else {
        this.fetchUserInfo()
      }
    },
    fetchUserInfo() {
      const storeUser = store.getters.getUser
      if (storeUser) {
        const newUserInfo = {
          id: storeUser.id || '',
          name: storeUser.username || '',
          password: '',
          role: 'employee',
          status: 'active'
        }
        this.userInfo = newUserInfo
        this.originalInfo = { ...newUserInfo }
      }
    }
  },
  created() {
    this.fetchUserInfo()
  }
}
</script>

<style scoped>
.user-profile {
  padding: 20px;
}

.profile-form {
  max-width: 600px;
  margin: 20px auto;
}

h1 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}
</style>